﻿using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Mirco.Extensions.Web
{
    public static class DependencyInjectionExtension
    {
        public static IServiceCollection RegisterApplicationServices(this IServiceCollection sc)
        {
            var assembly = Assembly.Load("Byt.Tpl.app.services");
            return Register(sc, assembly, "Service");
        }

        public static IServiceCollection RegisterDomainServices(this IServiceCollection sc)
        {
            var assembly = Assembly.Load("Byt.Tpl.domain.services");
            return Register(sc, assembly, "Service");
        }

        public static IServiceCollection RegisterRepositories(this IServiceCollection sc)
        {
            var assembly = Assembly.Load("Byt.Tpl.repositories");
            return Register(sc, assembly, "Repository");
        }

        public static IServiceCollection RegisterQueries(this IServiceCollection sc)
        {
            var assembly = Assembly.Load("Byt.Tpl.repositories");
            return Register(sc, assembly, "Query");
        }

        public static IServiceCollection RegisterProxies(this IServiceCollection sc)
        {
            var assembly = Assembly.Load("Byt.Tpl.proxies");
            return Register(sc, assembly, "Proxy");
        }

        private static IServiceCollection Register(IServiceCollection services, Assembly assembly, string endWith)
        {
            var types = assembly.GetTypes().Where(w => w.Name.EndsWith(endWith) && w.IsClass && !w.IsAbstract);
            foreach (var type in types)
            {
                var interfaceTypes = type.GetInterfaces();
                foreach (var interfaceType in interfaceTypes)
                {
                    services.TryAddScoped(interfaceType, type);
                }
            }

            return services;
        }
    }
}
